package utils

import (
	"fmt"
	"log"
	"time"

	"../../model"
	"github.com/robfig/cron"
)

func demo1() {
	fmt.Println("demo1")
}

func demo2() {
	fmt.Println("demo2")
}

func CronSetUp() {

	c := cron.New()

	c.AddFunc("*/20 * * * * *", func() {
		dict := model.GetCronTime()
		Cron(dict)
	})

	c.Start()

	t1 := time.NewTimer(time.Second * 10)
	for {
		select {
		case <-t1.C:
			t1.Reset(time.Second * 10)
		}
	}

}

func Cron(dict map[string]string) {
	log.Println("Starting...")
	c := cron.New()

	for k, v := range dict {
		fmt.Println(k, v)
		spec := fmt.Sprintf("*/%s * * * * *", v)

		if k == "urlTime" {
			print("urlTime", spec)

			c.AddFunc(spec, func() {
				demo1()
			})
		} else if k == "emailTime" {
			print("emailTime", spec)

			c.AddFunc(spec, func() {
				demo2()
			})
		}
	}

	c.Start()

	t1 := time.NewTimer(time.Second * 10)
	for {
		select {
		case <-t1.C:
			t1.Reset(time.Second * 10)
		}
	}
}
